<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>书籍管理</span>
      </div>
      <div class="filter-container">
        <el-input
          v-model="listQuery.goodsName"
          placeholder="书籍名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-select v-model="listQuery.category" placeholder="分类" clearable class="filter-item" style="width: 130px; margin-left: 10px;">
          <el-option label="文学类图书" value="文学类图书"/>
          <el-option label="教辅类图书" value="教辅类图书"/>
          <el-option label="科技类图书" value="科技类图书"/>
          <el-option label="生活类图书" value="生活类图书"/>
          <el-option label="艺术类图书" value="艺术类图书"/>
          <el-option label="历史类图书" value="历史类图书"/>
          <el-option label="少儿类图书" value="少儿类图书"/>
        </el-select>
        <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item" style="width: 130px; margin-left: 10px;">
          <el-option label="上架" value="上架" />
          <el-option label="下架" value="下架" />
          <el-option label="缺货" value="缺货" />
        </el-select>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" style="margin-left: 10px;">
          搜索
        </el-button>
        <el-button class="filter-item" @click="resetQuery" style="margin-left: 10px;">
          重置
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate">
          添加书籍
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="书籍名称" prop="goodsName" align="center" min-width="120" />
        <el-table-column label="作者" prop="author" align="center" width="100" />
        <el-table-column label="分类" prop="category" align="center" width="100" />
        <el-table-column label="价格" align="center" width="80">
          <template #default="scope">
            {{ scope.row.price ? `￥${scope.row.price}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="库存" prop="inventory" align="center" width="80" />
        <el-table-column label="销量" prop="sold" align="center" width="80" />
        <el-table-column label="商品图片" align="center" prop="pic" width="100">
          <template #default="scope">
            <div v-if="scope.row.pic" class="image-container">
              <el-image
                style="width: 60px; height: 60px; cursor: pointer;"
                :src="scope.row.pic"
                fit="cover"
                :preview-src-list="[]"
                :initial-index="0"
                @click="handlePreviewImg(scope.row.pic)"
              >
                <template #placeholder>
                  <div class="image-slot">
                    <el-icon><Loading /></el-icon>
                  </div>
                </template>
                <template #error>
                  <div class="image-slot">
                    <el-icon><PictureFilled /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '上架' ? 'success' : scope.row.status === '下架' ? 'info' : 'warning'">
              {{ scope.row.status === '上架' ? '上架' : scope.row.status === '下架' ? '下架' : '缺货' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleUpdate(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.pageNum"
        :limit.sync="listQuery.pageSize"
        @pagination="handlePagination"
      />
    </el-card>

    <el-dialog 
      v-model="dialogFormVisible"
      :title="dialogTitle" 
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="书籍名称" prop="goodsName">
          <el-input v-model="temp.goodsName" placeholder="请输入书籍名称"/>
        </el-form-item>
        
        <el-form-item label="作者" prop="author">
          <el-input v-model="temp.author" placeholder="请输入作者"/>
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select v-model="temp.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="文学类图书" value="文学类图书"/>
            <el-option label="教辅类图书" value="教辅类图书"/>
            <el-option label="科技类图书" value="科技类图书"/>
            <el-option label="生活类图书" value="生活类图书"/>
            <el-option label="艺术类图书" value="艺术类图书"/>
            <el-option label="历史类图书" value="历史类图书"/>
            <el-option label="少儿类图书" value="少儿类图书"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="temp.is_discount" label="原价" prop="original_price">
          <el-input-number v-model="temp.original_price" :precision="2" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item v-else label="价格" prop="price">
          <el-input-number v-model="temp.price" :precision="2" :step="0.1" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item v-if="temp.is_discount" label="现价">
          <el-input :value="(temp.original_price * 0.8).toFixed(2)" disabled />
        </el-form-item>

        <el-form-item label="库存" prop="inventory">
          <el-input-number 
            v-model="temp.inventory" 
            :min="0" 
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="上架" value="上架"/>
            <el-option label="下架" value="下架"/>
            <el-option label="缺货" value="缺货"/>
          </el-select>
        </el-form-item>

        <el-form-item label="封面图片" prop="pic">
          <el-upload
            class="avatar-uploader"
            :action="''"
            :show-file-list="false"
            :http-request="handleManualUpload"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="temp.pic" :src="temp.pic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>

        <el-form-item label="描述" prop="notes">
          <el-input
            v-model="temp.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入书籍描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-model="previewDialogVisible"
      width="auto"
      top="10vh"
      :show-close="true"
      :close-on-click-modal="true"
    >
      <div style="text-align:center;min-width:300px;min-height:300px;">
        <img
          :src="previewImgUrl"
          :style="{
            maxWidth: '80vw',
            maxHeight: '80vh',
            transform: `scale(${previewImgScale})`,
            transition: 'transform 0.2s'
          }"
          @wheel="handleImgWheel"
          draggable="false"
        />
        <div style="margin-top:10px;color:#888;">滚轮缩放，当前：{{ (previewImgScale*100).toFixed(0) }}%</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { page, save, deleteByIds, uploadPic } from '@/api/goods'
import { selectShop } from '@/api/shop'
import Pagination from '@/components/Pagination'
import { Search, Plus, Loading, PictureFilled } from '@element-plus/icons-vue'

export default {
  name: 'GoodsView',
  components: {
    Pagination,
    Search,
    Plus,
    Loading,
    PictureFilled
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        goodsName: undefined,
        category: undefined,
        status: undefined
      },
      shopOptions: [],
      temp: {
        id: undefined,
        goodsName: '',
        price: 0,
        inventory: 0,
        status: '上架',
        pic: '',
        notes: '',
        category: '',
        author: '',
        originalImg: '',
        fileID: '',
        is_discount: false,
        original_price: 0
      },
      dialogFormVisible: false,
      dialogTitle: '',
      rules: {
        goodsName: [{ required: true, message: '请输入书籍名称', trigger: 'blur' }],
        author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
        category: [{ required: true, message: '请选择分类', trigger: 'change' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        inventory: [{ required: true, message: '请输入库存', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        pic: [{ required: true, message: '请上传封面图片', trigger: 'change' }]
      },
      multipleSelection: [],
      previewDialogVisible: false,
      previewImgUrl: '',
      previewImgScale: 1
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        const response = await page(this.listQuery)
        
        if (response && response.result && response.result.data) {
          const { list, total, pageSize } = response.result.data
          
          const processedList = await Promise.all(list.map(async item => {
            let imageUrl = ''
            
            if (item.img) {
              try {
                const result = await this.$appCloud.callFunction({
                  name: 'Book',
                  data: {
                    action: 'getImageUrl',
                    fileID: item.img // 直接使用完整的fileID
                  }
                })
                if (result.result && result.result.code === 200) {
                  imageUrl = result.result.url || result.result.data.tempFileURL
                }
              } catch (error) {
                console.error('获取图片URL失败:', error)
              }
            }
            
            let status = item.status
            if (typeof status === 'number') {
              status = status === 1 ? '上架' : (status === 0 ? '下架' : '缺货')
            }
            
            return {
              id: item._id,
              goodsName: item.name || item.description,
              price: item.price || 0,
              inventory: item.stock || 0,
              sold: item.sale || 0,
              status: status,
              pic: imageUrl || null, // 如果没有URL则设为null
              fileID: item.img, // 保存完整的fileID
              notes: item.description || '',
              category: item.category || '',
              author: item.author || ''
            }
          }))
          
          this.list = processedList
          this.total = total || list.length
          this.listQuery.pageSize = pageSize || 10
        } else {
          this.list = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取书籍列表失败:', error)
        this.list = []
        this.total = 0
        this.$message.error('获取书籍列表失败')
      }
      this.listLoading = false
    },
    async getShopOptions() {
      try {
        const { data } = await selectShop()
        this.shopOptions = data
      } catch (error) {
        console.error('获取书店列表失败:', error)
      }
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.listQuery = {
        pageNum: 1,
        pageSize: 10,
        goodsName: undefined,
        category: undefined,
        status: undefined
      }
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        goodsName: '',
        price: 0,
        inventory: 0,
        status: '上架',
        pic: '',
        notes: '',
        category: '',
        author: '',
        originalImg: '',
        fileID: '',
        is_discount: false,
        original_price: 0
      }
    },
    handleCreate() {
      console.log('handleCreate clicked')
      this.resetTemp()
      this.dialogTitle = '添加书籍'
      this.dialogFormVisible = true
      console.log('dialogFormVisible set to:', this.dialogFormVisible)
      this.$nextTick(() => {
        console.log('nextTick - dialog should be visible')
        if (this.$refs['dataForm']) {
          this.$refs['dataForm'].clearValidate()
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      // 保存完整的fileID
      this.temp.fileID = row.fileID
      this.dialogTitle = '编辑书籍'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        if (this.$refs['dataForm']) {
          this.$refs['dataForm'].clearValidate()
        }
      })
    },
    async submitForm() {
      try {
        await new Promise((resolve, reject) => {
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              resolve()
            } else {
              reject(new Error('请填写完整所有必填字段'))
            }
          })
        })

        await this.$initAuth()
        
        const loading = this.$loading({
          lock: true,
          text: '保存中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        try {
          let submitData = {
            id: this.temp.id,
            book: {
              name: this.temp.goodsName,
              author: this.temp.author,
              category: this.temp.category,
              description: this.temp.notes,
              stock: Number(this.temp.inventory),
              status: this.temp.status,
              img: this.temp.fileID, // 使用完整的fileID
              sale: Number(this.temp.sold || 0),
              is_discount: this.temp.is_discount || false
            }
          }
          if (this.temp.is_discount) {
            submitData.book.original_price = Number(this.temp.original_price)
          } else {
            submitData.book.price = Number(this.temp.price)
          }

          if (!submitData.book.name) throw new Error('书籍名称不能为空')
          if (!submitData.book.author) throw new Error('作者不能为空')
          if (!submitData.book.category) throw new Error('分类不能为空')
          if (this.temp.is_discount) {
            if (submitData.book.original_price < 0) throw new Error('原价不能为负数')
          } else {
            if (submitData.book.price < 0) throw new Error('价格不能为负数')
          }
          if (submitData.book.stock < 0) throw new Error('库存不能为负数')
          if (!submitData.book.img) throw new Error('请上传封面图片')

          const result = await save(submitData)
          
          loading.close()
          this.dialogFormVisible = false
          this.$message({
            type: 'success',
            message: this.temp.id ? '更新成功!' : '添加成功!'
          })
          this.getList()
        } catch (error) {
          loading.close()
          throw error
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error(error.message || '保存失败，请重试')
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    async handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的书籍')
        return
      }
      
      try {
        await this.$confirm('确认删除选中的书籍吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 由于云函数限制，我们需要逐个删除
        for (const item of this.multipleSelection) {
          await deleteByIds(item.id)
        }
        
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除书籍失败:', error)
          this.$message.error(error.message || '删除失败')
        }
      }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该书籍吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await deleteByIds(row.id)
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除书籍失败:', error)
          this.$message.error(error.message || '删除失败')
        }
      }
    },
    async handleManualUpload(options) {
      try {
        await this.$initAuth()
        const loading = this.$loading({
          lock: true,
          text: '上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        const file = options.file
        const fileType = file.type.split('/')[1]
        const fileName = `${Date.now()}.${fileType}`

        // 转换为 base64
        const reader = new FileReader()
        const base64Promise = new Promise((resolve, reject) => {
          reader.onload = () => resolve(reader.result.split(',')[1])
          reader.onerror = error => reject(error)
          reader.readAsDataURL(file)
        })

        const base64Data = await base64Promise

        // 调用云函数上传图片
        const uploadResult = await this.$appCloud.callFunction({
          name: 'Book',
          data: {
            action: 'uploadImage',
            file: {
              name: fileName,
              data: base64Data,
              type: file.type
            }
          }
        })

        if (uploadResult.result && uploadResult.result.code === 200) {
          const fileID = uploadResult.result.fileID
          // 获取临时访问链接
          const urlResult = await this.$appCloud.callFunction({
            name: 'Book',
            data: {
              action: 'getImageUrl',
              fileID: fileID
            }
          })

          if (urlResult.result && urlResult.result.code === 200) {
            this.temp.pic = urlResult.result.url || urlResult.result.data.tempFileURL
            this.temp.fileID = fileID // 保存完整的fileID
            loading.close()
            this.$message.success('上传成功')
          } else {
            throw new Error('获取图片预览链接失败')
          }
        } else {
          throw new Error('上传失败')
        }
      } catch (error) {
        console.error('上传图片失败:', error)
        this.$message.error('上传失败: ' + (error.message || '未知错误'))
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 处理图片URL的方法
    async getImageUrl(fileID) {
      if (!fileID) return '';
      
      try {
        if (fileID.startsWith('cloud://')) {
          const app = this.$appCloud;
          const result = await app.callFunction({
            name: 'Book',
            data: {
              action: 'getImageUrl',
              fileID: fileID
            }
          });
          
          if (result.result && result.result.code === 200) {
            return result.result.url;
          }
        }
        return fileID;
      } catch (err) {
        console.error('获取图片URL失败:', err);
        return '';
      }
    },
    handlePagination({ page, limit }) {
      this.listQuery.pageNum = page;
      this.listQuery.pageSize = limit;
      this.getList();
    },
    handlePreviewImg(url) {
      this.previewImgUrl = url
      this.previewImgScale = 1
      this.previewDialogVisible = true
    },
    handleImgWheel(e) {
      e.preventDefault()
      let scale = this.previewImgScale
      if (e.deltaY < 0) {
        scale += 0.1
      } else {
        scale -= 0.1
      }
      scale = Math.max(0.2, Math.min(5, scale))
      this.previewImgScale = scale
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.el-icon {
  font-size: 20px;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}
</style>